Wrapper libraries (or library wrappers) consist of a thin layer of code (a "shim") which translates a library's existing interface into a compatible interface. This is done for several reasons:
Wrapper libraries can be implemented using the Adapter pattern, Facade pattern, and to a lesser extent, Proxy pattern design patterns.
// previous declarations... int pthread_mutex_init(pthread_mutex_t* mutex , const pthread_mutexattr_t* attr); int pthread_mutex_destroy(pthread_mutex_t* mutex); int pthread_mutex_lock(pthread_mutex_t* mutex); int pthread_mutex_unlock(pthread_mutex_t* mutex); // more functions...
import
export namespace org::posix {
// previous wrappers...
class ThreadMutex {
private:
class ThreadLock {
private:
// more wrappers...
}
::pthread_mutex_t mutex;
friend class ThreadLock;
void lock() noexcept {
::pthread_mutex_lock(&mutex);
}
void unlock() noexcept {
::pthread_mutex_unlock(&mutex);
}
public:
ThreadMutex() {
::pthread_mutex_init(&mutex, 0);
}
~ThreadMutex() {
::pthread_mutex_destroy(&mutex);
}
};
ThreadMutex& mutex;
public:
explicit ThreadLock(ThreadMutex& mutex):
mutex{mutex} {
mutex.lock();
}
~ThreadLock() {
mutex.unlock();
}
};
The original C interface can be regarded as error prone, particularly in the case where users of the library forget to unlock an already locked mutex. The new interface effectively utilizes resource acquisition is initialization (RAII) in the new and classes to ensure s are eventually unlocked and objects are automatically released.
The above code closely mimics the implementation of and classes from Boost which are part of the Boost.Thread library.
In order to achieve this, languages like Java provide a mechanism called foreign function interface that makes this possible. Some examples of these mechanisms include:
|
|